package com.diancan.modules.admin.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diancan.common.Result;
import com.diancan.domain.Good;
import com.diancan.domain.Orders;
import com.diancan.domain.Tabs;
import com.diancan.modules.good.GoodService;
import com.diancan.modules.good.tabs.TabsService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.UUID;

@RestController
@RequestMapping("adminGood")
@CrossOrigin
public class AdminGoodController {
    @Value("${file.location}")
    String filelocation;
    @Value("${file.path}")
    String filepath;
    @Value("${file.domainName}")
    String domainName;

    private final GoodService goodService;
    private final TabsService tabsService;

    public AdminGoodController(GoodService goodService, TabsService tabsService) {
        this.goodService = goodService;
        this.tabsService = tabsService;
    }

    // 文件上传
    @PostMapping("fileUpload")
    @SneakyThrows
    public Result fileUpload(MultipartFile file) {
        System.out.println(file.getOriginalFilename());
        if (file == null || file.isEmpty()) {
            return Result.buildFailureResult("请传入文件");
        } else {
            // 生成文件名
            String officialSealFileName = UUID.randomUUID().toString().replace("-", "").substring(0, 16) +
                    file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // 设置文件保存路径
            String officialSealFilePath = filelocation + "good";
            // 创建路径 可以事先手动创建好
            Files.createDirectories(Paths.get(officialSealFilePath));
            System.out.println(officialSealFilePath);
            System.out.println(officialSealFileName);
            // 保存文件
            file.transferTo(Path.of(officialSealFilePath, officialSealFileName));
            // 返回 url
            return Result.buildSuccessResult(domainName + "good/" + officialSealFileName);
        }
    }

    // 获取全部菜品
    @GetMapping("getAllGoog")
    public Result getAllGoog() {
        QueryWrapper<Good> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        return Result.buildSuccessResult(goodService.list(wrapper));
    }

    // 添加菜品
    @PostMapping("addGood")
    public Result addGood(@RequestBody Good good) {
        if (good.getTabId() != null) {
            good.setTabName(tabsService.getById(good.getTabId()).getName());
        }

        return Result.buildSuccessResult(goodService.save(good));
    }

    // 修改菜品
    @PostMapping("updateGood")
    public Result updateGood(@RequestBody Good good) {
        if (good.getTabId() != null) {
            good.setTabName(tabsService.getById(good.getTabId()).getName());
        }

        return Result.buildSuccessResult(goodService.updateById(good));
    }

    // 删除菜品
    @GetMapping("deleteGood")
    public Result deleteGood(Integer id) {
        if (id == null) {
            return Result.buildFailureResult("id为空");
        }
        return Result.buildSuccessResult(goodService.removeById(id));
    }

    // 查询菜品
    @GetMapping("searchGood")
    public Result searchGood(String key) {
        QueryWrapper<Good> wrapper = new QueryWrapper<>();
        if (key == null || "".equals(key)) {
            wrapper.orderByDesc("id");
        } else {
            wrapper.like("name", key).or().like("tab_id", key).or().eq("tab_name", key).orderByDesc("id");
        }
        return Result.buildSuccessResult(goodService.list(wrapper));
    }

    // 上架/下架
    @GetMapping("putaway")
    public void putaway(Integer id) {
        if (id != null) {
            Good good = goodService.getById(id);
            if (good != null) {
                good.setPutaway(Math.abs(good.getPutaway() - 1));
                goodService.updateById(good);
            }
        }
    }

    // 获取分类
    @GetMapping("getAllTab")
    public Result getAllTab(){
        QueryWrapper<Tabs> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("sort").orderByAsc("id");
        return Result.buildSuccessResult(tabsService.list(wrapper));
    }

    // 添加分类
    @PostMapping("addTab")
    public Result addTab(@RequestBody Tabs tab) {
        if (tab.getName() == null) {
            return Result.buildFailureResult("分类名为空");
        }
        return Result.buildSuccessResult(tabsService.save(tab));
    }

    // 修改分类
    @PostMapping("updataTab")
    public Result updataTab(@RequestBody Tabs tab) {
        if (tab.getId() == null) {
            return Result.buildFailureResult("分类id为空");
        }
        if (tab.getName() == null) {
            return Result.buildFailureResult("分类名为空");
        }
        return Result.buildSuccessResult(tabsService.updateById(tab));
    }

    // 删除分类
    @GetMapping("deleteTab")
    @Transactional
    public Result deleteTab(Integer id) {
        if (id == null) {
            return Result.buildFailureResult("id为空");
        }
        QueryWrapper<Good> wrapper = new QueryWrapper<>();
        wrapper.eq("tab_id",id);
        ArrayList<Good> goods = (ArrayList<Good>) goodService.list(wrapper);
        for (Good g:goods){
            g.setTabId(null);
            g.setTabName(null);
        }
        goodService.updateBatchById(goods);
        return Result.buildSuccessResult(tabsService.removeById(id));
    }
}
